<template>
  <el-dialog title="选择店铺位置" v-model="dialogVisible" width="80%">
    <div class="map-container">
      <!-- 百度地图容器 -->
      <baidu-map
        class="bm-view"
        :center="mapCenter"
        :zoom="15"
        @dblclick="handleMapClick"
        @ready="mapInit"
      >
        <!-- 自动定位组件 -->
        <bm-geolocation
          anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
          :showAddressBar="true"
          :autoLocation="true"
          @locationSuccess="handleLocationSuccess"
        />

        <!-- 搜索框 -->
        <bm-local-search
          ref="localSearch"
          :keyword="searchKeyword"
          :auto-viewport="true"
          @searchcomplete="handleSearchComplete"
        />

        <!-- 标记点 -->
        <bm-marker
          v-if="currentPoint"
          :position="currentPoint"
          :dragging="true"
          animation="BMAP_ANIMATION_BOUNCE"
        />
      </baidu-map>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索店铺/地址"
          @keyup.enter="triggerSearch"
        >
          <template #append>
            <el-button @click="triggerSearch">搜索</el-button>
          </template>
        </el-input>
      </div>
    </div>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmSelection">确认选择</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang='ts'>
import { ref, watch, onMounted, defineProps, emit } from 'vue'
import { ElMessage } from 'element-plus'
import {
  BaiduMap,
  BmMarker,
  BmLocalSearch,
  BmGeolocation,
} from "vue-baidu-map-3x";

// 定义类型
interface Point {
  lng: number
  lat: number
}

interface AddressInfo {
  name: string
  address: string
  point: Point
}

// 定义props
const props = defineProps<{
  modelValue: boolean
}>()

// 定义emit
const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'confirm', value: AddressInfo): void
}>()

// 响应式数据
const dialogVisible = ref(props.modelValue)
const showSearchBox = ref(true)
const mapCenter = ref<Point>({ lng: 116.404, lat: 39.915 })
const currentPoint = ref<Point | null>(null)
const searchKeyword = ref('')
const addressInfo = ref<AddressInfo>({
  name: "",
  address: "",
  point: { lng: 116.404, lat: 39.915 },
})
const BMap = ref<any>(null)
const map = ref<any>(null)
const localSearch = ref<any>(null)
const initLocation = ref(false)

// 监听props变化
watch(() => props.modelValue, (val) => {
  dialogVisible.value = val
})

// 监听对话框显示状态变化
watch(dialogVisible, (val) => {
  emit('update:modelValue', val)
})

// 地图初始化完成
const mapInit = ({ BMap: bmap, map: mapInstance }: any) => {
  BMap.value = bmap
  map.value = mapInstance
}

// 处理定位成功
const handleLocationSuccess = (result: any) => {
  const position = result.point
  
  // 更新地图中心点
  mapCenter.value = {
    lng: position.lng,
    lat: position.lat,
  }
  
  // 保存当前定位点
  currentPoint.value = position
  
  // 执行逆向地理编码
  reverseGeocode(position)
  
  // 更新初始化状态
  initLocation.value = true
  
  console.log("定位成功：", {
    coordinates: position,
    accuracy: result.accuracy,
  })
}

// 处理地图双击事件
const handleMapClick = (e: any) => {
  currentPoint.value = e.point
  reverseGeocode(e.point)
}

// 触发搜索
const triggerSearch = () => {
  if (!searchKeyword.value.trim()) return
  
  // 强制触发搜索组件更新
  setTimeout(() => {
    if (localSearch.value) {
      localSearch.value.search(searchKeyword.value)
    }
  }, 0)
}

// 处理搜索完成
const handleSearchComplete = (results: any) => {
  if (results && results.getResults().length) {
    const poi = results.getResults()[0]
    currentPoint.value = poi.point
    mapCenter.value = poi.point
    addressInfo.value = {
      name: poi.title,
      address: poi.address,
      point: poi.point,
    }
  } else {
    ElMessage.error("未找到相关地点")
  }
}

// 逆向地理编码获取地址详情
const reverseGeocode = (point: Point) => {
  if (!BMap.value) return
  
  const geocoder = new BMap.value.Geocoder()
  geocoder.getLocation(point, (result: any) => {
    if (result) {
      addressInfo.value = {
        name: result.business || result.address,
        address: result.address,
        point: point,
      }
    }
  })
}

// 处理选择项
const handleSelectItem = (item: any) => {
  if (!map.value || !BMap.value) return
  
  // 清除旧标记
  map.value.clearOverlays()
  
  // 创建新标记
  const point = new BMap.value.Point(item.point.lng, item.point.lat)
  const marker = new BMap.value.Marker(point)
  map.value.addOverlay(marker)
  
  // 更新地图中心点
  map.value.panTo(point)
  
  // 隐藏搜索框和列表
  showSearchBox.value = false
}

// 确认选择
const confirmSelection = () => {
  if (addressInfo.value.point) {
     console.log("选择地址：", addressInfo.value)
    emit('confirm', addressInfo.value)
    dialogVisible.value = false
  } else {
    ElMessage.warning("请先选择位置")
  }
}
</script>

<style scoped>
.map-container {
  position: relative;
  height: 600px;
}

.bm-view {
  width: 100%;
  height: 100%;
}

.search-bar {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 999;
  width: 300px;
  background: rgba(255, 255, 255, 0.8);
  padding: 10px;
  border-radius: 4px;
}
</style>
